package view


import android.content.Context
import android.graphics.Color
import android.media.MediaPlayer
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.VideoView
import app.AppContext
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.danikula.videocache.HttpProxyCacheServer
import com.hontech.kdxclient.R
import ext.log
import manager.TaskManager
import mvc.model.MediaData
import mvc.model.PictureData
import mvc.model.VideoData


class VideoPlayer : VideoView {
    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = getDefaultSize(0, widthMeasureSpec)
        val height = getDefaultSize(0, heightMeasureSpec)
        setMeasuredDimension(width, height)
    }
}

class CustomMediaPlayer : FrameLayout, Runnable, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
    companion object {
        private val httpProxy =
            HttpProxyCacheServer.Builder(AppContext).maxCacheFilesCount(100).maxCacheSize(1024 * 1024 * 1024).build()
    }

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    private val video: VideoPlayer
    private val image: ImageView
    private var videoData = VideoData("", "00:00", "23:59")
    private var pictureData = PictureData("", 10000, "00:00", "23:59")
    private var isPlayPicture = false
    private var isPlayVideo = false
    var onCompletion = {}

    init {
        video = VideoPlayer(context)
        val params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT,
            Gravity.CENTER
        )
        video.layoutParams = params
        video.setOnErrorListener(this)
        video.setOnCompletionListener(this)
        video.visibility = View.GONE
        addView(video)

        image = ImageView(context)
        image.layoutParams = params
        image.scaleType = ImageView.ScaleType.FIT_XY
        image.setImageResource(R.drawable.ic_logo)
        addView(image)
        setBackgroundColor(Color.WHITE)
    }

    fun setUp(data: MediaData) {
        initPlayer()
        when (data) {
            is VideoData -> {
                videoData = data
                setVideo(data.url)
            }

            is PictureData -> {
                pictureData = data
                setPicture(data.url, data.timeOut)
            }
        }
    }

    fun onPause() {
        if (isPlayVideo) {
            video.pause()
            return
        }

        if (isPlayPicture) {
            TaskManager.UiHandler.removeCallbacks(this)
        }
    }

    fun onResume() {
        if (isPlayVideo) {
            setVideo()
            return
        }

        if (isPlayPicture) {
            setPicture()
        }
    }

    private fun initPlayer() {
        video.pause()
        TaskManager.UiHandler.removeCallbacks(this)
    }

    private fun setVideo(url: String = videoData.url) {
        isPlayVideo = true
        isPlayPicture = false
        image.visibility = View.GONE
        video.visibility = View.VISIBLE
        val local = httpProxy.getProxyUrl(url)
        video.setVideoPath(local)
        video.start()
    }

    private fun setPicture(url: String = pictureData.url, timeOut: Long = pictureData.timeOut) {
        isPlayVideo = false
        isPlayPicture = true
        image.visibility = View.VISIBLE
        video.visibility = View.GONE

        val options = RequestOptions()
        options.error(R.drawable.ic_logo)
        options.diskCacheStrategy(DiskCacheStrategy.ALL)
        options.skipMemoryCache(true)

        Glide.with(context).load(url).apply(options).transition(DrawableTransitionOptions.withCrossFade()).into(image)

        TaskManager.UiHandler.postDelayed(this, timeOut)
    }

    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        log("播放异常")
        video.pause()
        video.stopPlayback()
        onCompletion()
        return true
    }

    override fun onCompletion(mp: MediaPlayer?) {
        onCompletion()
    }

    override fun run()  // 图片播放时间到了
    {
        onCompletion()
    }

}